import json
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
import numpy as np
from collections import Counter
import seaborn as sns
import re
import jieba
from wordcloud import WordCloud
import os
import sys
import argparse

# 设置中文显示
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

# 配置信息
CONFIG = {
    # 默认配置，可以在命令行参数中覆盖
    "restaurant_file": "餐厅列表_1742290405123.json",  # 餐厅数据文件路径
    "order_file": "2025元旦后订单_1742290420499.json",       # 订单数据文件路径
    "output_dir": "analysis_results", # 输出目录
    "specific_restaurant_id": 20227,   # 指定分析的餐厅ID
    "show_plots": False,              # 是否显示图表（除了保存外）
}

class RestaurantAnalyzer:
    def __init__(self, restaurant_file, order_file, output_dir="analysis_results"):
        """
        初始化分析器

        Args:
            restaurant_file: 餐厅数据文件路径
            order_file: 订单数据文件路径
            output_dir: 输出目录
        """
        self.output_dir = output_dir

        # 创建结果目录
        os.makedirs(self.output_dir, exist_ok=True)

        print(f"正在加载数据...")
        print(f"餐厅数据文件: {restaurant_file}")
        print(f"订单数据文件: {order_file}")

        # 加载餐厅数据
        try:
            with open(restaurant_file, 'r', encoding='utf-8') as f:
                restaurant_data = json.load(f)

            # 处理餐厅数据
            if isinstance(restaurant_data, dict) and 'Sheet1' in restaurant_data:
                self.restaurants_df = pd.DataFrame(restaurant_data['Sheet1'])
            else:
                self.restaurants_df = pd.DataFrame(restaurant_data)

            print(f"成功加载餐厅数据，共 {len(self.restaurants_df)} 条记录")
        except Exception as e:
            print(f"加载餐厅数据出错: {e}")
            self.restaurants_df = pd.DataFrame()

        # 加载订单数据
        try:
            # 使用更健壮的方式逐行读取JSON，避免Extra data错误
            with open(order_file, 'r', encoding='utf-8') as f:
                content = f.read()
                # 尝试清理JSON格式问题
                content = content.strip()
                # 确保JSON数组格式正确
                if not content.startswith('['):
                    content = '[' + content
                if not content.endswith(']'):
                    content = content + ']'
                # 替换可能导致解析错误的多余逗号
                content = re.sub(r',\s*]', ']', content)

            try:
                # 尝试解析整个JSON
                order_data = json.loads(content)
                self.orders_df = pd.DataFrame(order_data)
            except json.JSONDecodeError as e:
                print(f"完整解析订单数据失败，尝试逐行解析: {e}")
                # 如果整体解析失败，尝试逐行解析
                try:
                    # 将内容分割成独立的JSON对象
                    lines = re.findall(r'\{[^{}]*\}', content)
                    order_data = []
                    for line in lines:
                        try:
                            item = json.loads(line)
                            order_data.append(item)
                        except:
                            pass  # 忽略无法解析的行

                    if order_data:
                        self.orders_df = pd.DataFrame(order_data)
                    else:
                        print("无法解析任何订单数据")
                        self.orders_df = pd.DataFrame()
                except Exception as e2:
                    print(f"逐行解析订单数据也失败了: {e2}")
                    self.orders_df = pd.DataFrame()

            print(f"成功加载订单数据，共 {len(self.orders_df)} 条记录")
            # 打印列名以便调试
            print(f"订单数据列名: {list(self.orders_df.columns)}")

        except Exception as e:
            print(f"加载订单数据出错: {e}")
            self.orders_df = pd.DataFrame()

        # 清洗数据
        self._clean_data()

    def _clean_data(self):
        """清洗和预处理数据"""
        print("开始清洗数据...")

        # 清洗餐厅数据
        if '餐厅ID' in self.restaurants_df.columns:
            self.restaurants_df['餐厅ID'] = self.restaurants_df['餐厅ID'].astype(str)
            print(f"餐厅数据中的餐厅ID范围: {self.restaurants_df['餐厅ID'].unique()[:5]}...")

        # 显示订单数据框的信息
        if not self.orders_df.empty:
            print("订单数据关键字段情况:")
            for col in ['餐厅ID', 'rd_id', '订单创建时间', 'create_time', '菜详情']:
                if col in self.orders_df.columns:
                    non_null_count = self.orders_df[col].count()
                    print(f"  - {col}: {non_null_count}个非空值 ({non_null_count/len(self.orders_df)*100:.1f}%)")
                    if non_null_count > 0:
                        sample_values = self.orders_df[col].dropna().head(2).tolist()
                        print(f"    样本值: {sample_values}")

        # 处理订单数据中的餐厅ID
        self._process_restaurant_id()

        # 处理订单创建时间
        self._process_order_time()

        # 处理菜品数据
        self._process_dish_data()

        print("数据清洗完成")

    def _process_restaurant_id(self):
        """处理不同格式的餐厅ID"""
        # 检查并统一字段名 - 处理 rd_id 和 餐厅ID
        if 'rd_id' in self.orders_df.columns:
            print("处理'rd_id'字段...")
            # 将rd_id作为备份
            if '餐厅ID' not in self.orders_df.columns:
                self.orders_df['餐厅ID'] = self.orders_df['rd_id']
                print("已将'rd_id'字段映射为'餐厅ID'")
            else:
                # 如果已有餐厅ID列但大多为空，则尝试用rd_id填充
                null_mask = self.orders_df['餐厅ID'].isnull() | (self.orders_df['餐厅ID'] == '') | (self.orders_df['餐厅ID'] == 'nan')
                if null_mask.sum() > 0:
                    self.orders_df.loc[null_mask, '餐厅ID'] = self.orders_df.loc[null_mask, 'rd_id']
                    print(f"已用'rd_id'填充{null_mask.sum()}个空的'餐厅ID'值")

        # 清洗餐厅ID
        if '餐厅ID' in self.orders_df.columns:
            # 尝试修复无效的餐厅ID值
            invalid_mask = self.orders_df['餐厅ID'].isnull() | (self.orders_df['餐厅ID'] == '') | (self.orders_df['餐厅ID'] == 'nan')
            invalid_count = invalid_mask.sum()
            if invalid_count > 0:
                print(f"发现{invalid_count}个无效的餐厅ID值，尝试修复...")

                # 尝试从餐厅名称或其他字段推断餐厅ID
                if '餐厅名称' in self.orders_df.columns:
                    for idx, row in self.orders_df[invalid_mask].iterrows():
                        if pd.notna(row.get('餐厅名称')):
                            # 在餐厅数据中查找匹配的餐厅名称
                            matches = self.restaurants_df[self.restaurants_df['餐厅名称'] == row['餐厅名称']]
                            if not matches.empty:
                                self.orders_df.at[idx, '餐厅ID'] = matches.iloc[0]['餐厅ID']

                    # 统计修复后的情况
                    fixed_count = invalid_mask.sum() - self.orders_df['餐厅ID'].isnull().sum()
                    print(f"通过餐厅名称匹配修复了{fixed_count}个餐厅ID")

            # 去除多余的空格并转为字符串
            self.orders_df['餐厅ID'] = self.orders_df['餐厅ID'].astype(str).str.strip()
            # 过滤无效值
            self.orders_df.loc[self.orders_df['餐厅ID'].isin(['nan', 'None', '']), '餐厅ID'] = None
            print(f"清洗后有效餐厅ID数量: {self.orders_df['餐厅ID'].notna().sum()}")
        else:
            print(f"警告：订单数据中既没有 '餐厅ID' 也没有 'rd_id' 字段。")

    def _process_order_time(self):
        """处理订单时间相关字段"""
        # 处理订单创建时间
        datetime_fields = []
        if '订单创建时间' in self.orders_df.columns:
            datetime_fields.append('订单创建时间')
        if 'create_time' in self.orders_df.columns:
            datetime_fields.append('create_time')

        time_field_processed = False
        for field in datetime_fields:
            if not time_field_processed:
                try:
                    print(f"尝试处理时间字段: {field}")
                    # 处理空值
                    self.orders_df[field] = self.orders_df[field].fillna('')

                    # 转换日期时间
                    date_series = pd.to_datetime(
                        self.orders_df[field].astype(str).str.strip(),
                        errors='coerce',
                        format='%Y-%m-%d %H:%M:%S'
                    )

                    # 如果大部分转换失败，尝试不同的格式
                    if date_series.isna().mean() > 0.5:
                        common_formats = [
                            '%Y-%m-%d %H:%M:%S',
                            '%Y/%m/%d %H:%M:%S',
                            '%d/%m/%Y %H:%M:%S',
                            '%m/%d/%Y %H:%M:%S',
                            '%Y-%m-%dT%H:%M:%S',
                            '%Y-%m-%d'
                        ]

                        for fmt in common_formats:
                            try:
                                date_series = pd.to_datetime(
                                    self.orders_df[field].astype(str).str.strip(),
                                    errors='coerce',
                                    format=fmt
                                )
                                if date_series.isna().mean() < 0.5:
                                    print(f"成功使用格式 {fmt} 解析大部分日期")
                                    break
                            except:
                                continue

                    # 如果转换成功
                    non_null_count = date_series.notna().sum()
                    if non_null_count > 0:
                        self.orders_df['订单创建时间'] = date_series
                        self.orders_df['订单日期'] = self.orders_df['订单创建时间'].dt.date
                        self.orders_df['订单小时'] = self.orders_df['订单创建时间'].dt.hour
                        self.orders_df['订单星期'] = self.orders_df['订单创建时间'].dt.dayofweek
                        print(f"成功处理 {non_null_count} 条订单时间记录")
                        time_field_processed = True
                    else:
                        print(f"无法解析{field}为有效日期时间")
                except Exception as e:
                    print(f"处理时间字段 {field} 时出错: {e}")

        if not time_field_processed:
            print("警告: 无法处理任何订单时间字段，时间分析功能将不可用")

    def _process_dish_data(self):
        """处理菜品数据"""
        dish_fields = []
        if '菜详情' in self.orders_df.columns:
            dish_fields.append('菜详情')
        if 'dishes' in self.orders_df.columns:
            dish_fields.append('dishes')

        for field in dish_fields:
            try:
                print(f"处理菜品字段: {field}")
                # 检查字段中非空值的数量
                non_null_count = self.orders_df[field].notna().sum()
                if non_null_count > 0:
                    print(f"发现 {non_null_count} 条非空菜品数据")

                    # 尝试解析菜品数据
                    self.orders_df['菜品列表'] = self.orders_df[field].apply(self._extract_dishes)
                    valid_dishes = self.orders_df['菜品列表'].apply(lambda x: len(x) if isinstance(x, list) else 0).sum()

                    if valid_dishes > 0:
                        print(f"成功解析 {valid_dishes} 个菜品")
                        break
                    else:
                        print(f"未能从 {field} 中提取有效菜品数据")
            except Exception as e:
                print(f"处理菜品字段 {field} 时出错: {e}")

        if '菜品列表' not in self.orders_df.columns or self.orders_df['菜品列表'].apply(lambda x: len(x) if isinstance(x, list) else 0).sum() == 0:
            print("警告: 无法解析任何菜品数据，菜品分析功能将不可用")
            self.orders_df['菜品列表'] = [[] for _ in range(len(self.orders_df))]

    def _extract_dishes(self, dishes_json_str):
        """从菜详情JSON字符串中提取菜品信息"""
        if not dishes_json_str or pd.isna(dishes_json_str):
            return []

        try:
            if isinstance(dishes_json_str, str):
                # 确保JSON字符串有效
                dishes_json_str = dishes_json_str.replace("'", '"').replace('\\', '\\\\')
                # 去除可能导致解析错误的字符
                dishes_json_str = re.sub(r'[\x00-\x1F\x7F]', '', dishes_json_str)
                # 尝试解析JSON
                try:
                    dishes = json.loads(dishes_json_str)
                    if isinstance(dishes, list):
                        return dishes
                    elif isinstance(dishes, dict):
                        return [dishes]
                except:
                    # 如果标准解析失败，尝试其他解析方法
                    try:
                        # 正则表达式提取可能的菜品信息
                        dish_matches = re.findall(r'\{"dishes_name":"([^"]+)"', dishes_json_str)
                        if dish_matches:
                            return [{"dishes_name": name} for name in dish_matches]
                    except:
                        pass
            elif isinstance(dishes_json_str, (list, dict)):
                # 如果已经是列表或字典，直接使用
                if isinstance(dishes_json_str, dict):
                    return [dishes_json_str]
                return dishes_json_str
            return []
        except:
            return []

    def analyze_popular_restaurants(self):
        """分析订单多的餐厅有哪些特点"""
        # 检查必要的数据
        if '餐厅ID' not in self.orders_df.columns:
            print("订单数据中缺少餐厅ID字段")
            return []

        # 计算每家餐厅的订单数
        restaurant_order_counts = self.orders_df['餐厅ID'].value_counts().reset_index()
        restaurant_order_counts.columns = ['餐厅ID', '订单数']

        # 合并餐厅信息
        restaurant_analysis = pd.merge(
            restaurant_order_counts,
            self.restaurants_df,
            on='餐厅ID',
            how='left'
        )

        # 检查是否有数据
        if restaurant_analysis.empty:
            print("没有找到餐厅订单数据")
            return []

        # 按订单数量排序
        restaurant_analysis = restaurant_analysis.sort_values('订单数', ascending=False)

        try:
            # 分析餐厅类型分布（如果有该字段）
            if '餐厅类型' in restaurant_analysis.columns and not restaurant_analysis['餐厅类型'].isna().all():
                restaurant_types = restaurant_analysis['餐厅类型'].value_counts()

                if len(restaurant_types) > 0:
                    plt.figure(figsize=(10, 6))
                    restaurant_types.plot(kind='pie', autopct='%1.1f%%')
                    plt.title('订单量按餐厅类型分布')
                    plt.tight_layout()
                    plt.savefig(os.path.join(self.output_dir, 'restaurant_types.png'))
                    plt.close()

            # 分析地区分布（如果有该字段）
            if '地址-州' in restaurant_analysis.columns and not restaurant_analysis['地址-州'].isna().all():
                state_distribution = restaurant_analysis['地址-州'].value_counts()

                if len(state_distribution) > 0:
                    plt.figure(figsize=(10, 6))
                    state_distribution.plot(kind='bar')
                    plt.title('订单量按州分布')
                    plt.xlabel('州')
                    plt.ylabel('餐厅数量')
                    plt.tight_layout()
                    plt.savefig(os.path.join(self.output_dir, 'state_distribution.png'))
                    plt.close()

            # 分析营业时间（如果有该字段）
            weekdays = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
            if all(day in restaurant_analysis.columns for day in weekdays):
                restaurant_analysis['营业天数'] = restaurant_analysis[weekdays].apply(
                    lambda x: sum(1 for day in x if not pd.isna(day) and day != ''), axis=1
                )

                plt.figure(figsize=(10, 6))
                plt.scatter(restaurant_analysis['营业天数'], restaurant_analysis['订单数'])
                plt.title('营业天数与订单数量关系')
                plt.xlabel('每周营业天数')
                plt.ylabel('订单数量')
                plt.tight_layout()
                plt.savefig(os.path.join(self.output_dir, 'business_days_orders.png'))
                plt.close()
        except Exception as e:
            print(f"绘制餐厅分析图表时出错: {e}")

        # 返回结果，确保至少包含这些字段
        columns = ['餐厅ID', '订单数']
        if '餐厅名称' in restaurant_analysis.columns:
            columns.append('餐厅名称')

        return restaurant_analysis.head(10)[columns].to_dict('records')

    def analyze_order_time_patterns(self):
        """分析订单爆发的时间"""
        if '订单创建时间' not in self.orders_df.columns:
            print("订单数据中缺少时间信息")
            return {"高峰小时": [], "高峰星期": []}

        try:
            # 按小时统计订单数
            if '订单小时' in self.orders_df.columns:
                hourly_orders = self.orders_df['订单小时'].value_counts().sort_index()

                # 按星期统计订单数
                weekday_orders = self.orders_df['订单星期'].value_counts().sort_index()
                weekday_names = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
                weekday_orders.index = [weekday_names[i] for i in weekday_orders.index if i < len(weekday_names)]

                # 绘制图表
                plt.figure(figsize=(12, 10))

                # 每小时订单量
                plt.subplot(2, 1, 1)
                hourly_orders.plot(kind='bar')
                plt.title('每小时订单量分布')
                plt.xlabel('小时')
                plt.ylabel('订单数量')

                # 每星期订单量
                plt.subplot(2, 1, 2)
                weekday_orders.plot(kind='bar')
                plt.title('每星期订单量分布')
                plt.xlabel('星期')
                plt.ylabel('订单数量')

                # 保存结果
                plt.tight_layout()
                plt.savefig(os.path.join(self.output_dir, 'time_analysis.png'))
                plt.close()

                # 找出订单高峰时段
                peak_hours = hourly_orders.sort_values(ascending=False).head(3)
                peak_days = weekday_orders.sort_values(ascending=False).head(3)

                return {
                    "高峰小时": peak_hours.index.tolist(),
                    "高峰星期": peak_days.index.tolist()
                }
            else:
                print("订单小时数据不存在")
                return {"高峰小时": [], "高峰星期": []}
        except Exception as e:
            print(f"分析订单时间模式时出错: {e}")
            return {"高峰小时": [], "高峰星期": []}

    def analyze_popular_dishes(self):
        """分析哪一类的菜更受欢迎"""
        if '菜品列表' not in self.orders_df.columns:
            print("订单数据中缺少菜品信息")
            return {"热门菜品": [], "热门菜品类别": []}

        try:
            # 提取所有菜品
            all_dishes = []
            dish_price_map = {}  # 用于记录菜品价格

            for _, row in self.orders_df.iterrows():
                dishes = row['菜品列表']
                if dishes and isinstance(dishes, list):
                    for dish in dishes:
                        if isinstance(dish, dict):
                            dish_name = dish.get('dishes_name', '')
                            if dish_name:
                                all_dishes.append(dish_name)
                                # 记录菜品价格
                                try:
                                    price = float(dish.get('unit_price', 0))
                                    if dish_name in dish_price_map:
                                        dish_price_map[dish_name].append(price)
                                    else:
                                        dish_price_map[dish_name] = [price]
                                except:
                                    pass

            # 如果没有菜品数据，返回空结果
            if not all_dishes:
                print("没有找到菜品数据")
                return {"热门菜品": [], "热门菜品类别": []}

            # 计算每种菜品的平均价格
            dish_avg_price = {dish: sum(prices)/len(prices) for dish, prices in dish_price_map.items()}

            # 计算菜品频率
            dish_counter = Counter(all_dishes)
            top_dishes = dish_counter.most_common(20)

            # 提取菜品类别
            dish_categories = self._extract_dish_categories(all_dishes)
            category_counter = Counter(dish_categories)
            top_categories = category_counter.most_common(10)

            # 绘制图表
            plt.figure(figsize=(15, 10))

            # 热门菜品条形图
            plt.subplot(2, 1, 1)
            dishes_df = pd.DataFrame(top_dishes, columns=['菜品名称', '点单次数'])
            dishes_df['平均价格'] = dishes_df['菜品名称'].map(dish_avg_price)
            dishes_df = dishes_df.sort_values('点单次数', ascending=False)

            if len(dishes_df) > 0:
                plt.barh(dishes_df['菜品名称'].head(10), dishes_df['点单次数'].head(10))
                plt.title('热门菜品TOP10')
                plt.xlabel('点单次数')
                plt.ylabel('菜品名称')

            # 菜品类别饼图
            plt.subplot(2, 1, 2)
            categories_df = pd.DataFrame(top_categories, columns=['菜品类别', '数量'])
            if len(categories_df) > 0:
                plt.pie(categories_df['数量'], labels=categories_df['菜品类别'], autopct='%1.1f%%')
                plt.title('菜品类别分布')

            # 保存结果
            plt.tight_layout()
            plt.savefig(os.path.join(self.output_dir, 'dish_analysis.png'))
            plt.close()

            return {
                "热门菜品": dishes_df[['菜品名称', '点单次数', '平均价格']].head(10).to_dict('records'),
                "热门菜品类别": categories_df.head(5).to_dict('records')
            }
        except Exception as e:
            print(f"分析热门菜品时出错: {e}")
            return {"热门菜品": [], "热门菜品类别": []}

    def _extract_dish_categories(self, dish_names):
        """提取菜品类别"""
        categories = []
        category_patterns = [
            (r'Roll', '寿司卷'),
            (r'Sushi', '寿司'),
            (r'Salad', '沙拉'),
            (r'Soup', '汤'),
            (r'Chicken', '鸡肉'),
            (r'Beef', '牛肉'),
            (r'Pork', '猪肉'),
            (r'Noodle', '面条'),
            (r'Rice', '米饭'),
            (r'Spicy', '辣味'),
            (r'Fried', '炸物'),
            (r'Vegetable', '蔬菜'),
            (r'Seafood', '海鲜'),
            (r'Dessert', '甜点')
        ]

        for dish in dish_names:
            found = False
            for pattern, category in category_patterns:
                if re.search(pattern, dish, re.IGNORECASE):
                    categories.append(category)
                    found = True
                    break
            if not found:
                categories.append('其他')

        return categories

    def analyze_restaurant_details(self, restaurant_id):
        """分析指定餐厅的详细情况"""
        # 检查订单数据中是否存在餐厅ID字段
        if '餐厅ID' not in self.orders_df.columns:
            print(f"错误：订单数据中缺少'餐厅ID'列。可用的列有：{', '.join(self.orders_df.columns)}")
            return {"错误": "订单数据中缺少'餐厅ID'列"}

        # 筛选指定餐厅
        restaurant_id = str(restaurant_id).strip()
        restaurant_orders = self.orders_df[self.orders_df['餐厅ID'].str.strip() == restaurant_id]

        if restaurant_orders.empty:
            return {"错误": f"没有找到ID为{restaurant_id}的餐厅订单"}

        try:
            # 查找餐厅信息
            restaurant_info = self.restaurants_df[self.restaurants_df['餐厅ID'].astype(str).str.strip() == restaurant_id]

            # 计算该餐厅的热门菜品
            all_dishes = []
            for _, row in restaurant_orders.iterrows():
                if '菜品列表' in row and row['菜品列表'] and isinstance(row['菜品列表'], list):
                    for dish in row['菜品列表']:
                        if isinstance(dish, dict):
                            dish_name = dish.get('dishes_name', '')
                            if dish_name:
                                try:
                                    price = float(dish.get('unit_price', 0))
                                    all_dishes.append((dish_name, price))
                                except:
                                    all_dishes.append((dish_name, 0))

            # 统计热门菜品
            dish_counter = Counter([dish[0] for dish in all_dishes])
            top_dishes = dish_counter.most_common(10)

            # 计算每个菜品的平均价格
            dish_prices = {}
            for dish_name, price in all_dishes:
                if dish_name in dish_prices:
                    dish_prices[dish_name].append(price)
                else:
                    dish_prices[dish_name] = [price]

            dish_avg_prices = {dish: sum(prices)/len(prices) for dish, prices in dish_prices.items()}

            # 分析订单时间分布
            time_analysis = {}
            if '订单创建时间' in restaurant_orders.columns and '订单小时' in restaurant_orders.columns:
                hourly_orders = restaurant_orders['订单小时'].value_counts().sort_index()
                weekday_orders = restaurant_orders['订单星期'].value_counts().sort_index()
                weekday_names = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
                weekday_orders.index = [weekday_names[i] for i in weekday_orders.index if i < len(weekday_names)]

                # 绘制图表
                plt.figure(figsize=(12, 10))

                # 热门菜品条形图
                plt.subplot(2, 1, 1)
                dishes_df = pd.DataFrame(top_dishes, columns=['菜品名称', '点单次数'])
                dishes_df['平均价格'] = dishes_df['菜品名称'].map(dish_avg_prices)

                if len(dishes_df) > 0:
                    plt.barh(dishes_df['菜品名称'], dishes_df['点单次数'])
                    plt.title(f'餐厅 {restaurant_id} 热门菜品')
                    plt.xlabel('点单次数')
                    plt.ylabel('菜品名称')

                # 每小时订单量
                plt.subplot(2, 2, 3)
                hourly_orders.plot(kind='bar')
                plt.title(f'餐厅 {restaurant_id} 每小时订单量')
                plt.xlabel('小时')
                plt.ylabel('订单数量')

                # 每星期订单量
                plt.subplot(2, 2, 4)
                weekday_orders.plot(kind='bar')
                plt.title(f'餐厅 {restaurant_id} 每星期订单量')
                plt.xlabel('星期')
                plt.ylabel('订单数量')

                # 保存结果
                plt.tight_layout()
                plt.savefig(os.path.join(self.output_dir, f'restaurant_{restaurant_id}_analysis.png'))
                plt.close()

                time_analysis = {
                    "高峰时段": hourly_orders.sort_values(ascending=False).head(3).index.tolist(),
                    "高峰星期": weekday_orders.sort_values(ascending=False).head(3).index.tolist()
                }

            # 返回餐厅分析结果
            result = {
                "餐厅ID": restaurant_id,
                "餐厅名称": restaurant_info['餐厅名称'].values[0] if not restaurant_info.empty else "未知",
                "订单总数": len(restaurant_orders),
                "热门菜品": [{"菜品名称": dish, "点单次数": count, "平均价格": dish_avg_prices.get(dish, 0)} for dish, count in top_dishes],
            }

            if time_analysis:
                result.update(time_analysis)

            if '订单总价' in restaurant_orders.columns:
                try:
                    result["平均订单金额"] = restaurant_orders['订单总价'].astype(float).mean()
                except:
                    pass

            return result
        except Exception as e:
            print(f"分析餐厅 {restaurant_id} 时出错: {e}")
            return {"错误": f"分析餐厅 {restaurant_id} 时出错: {e}"}

    def recommendations_for_increasing_orders(self):
        """提供增加订单数量的建议"""
        # 基于前面的分析结果提供建议
        peak_times = self.analyze_order_time_patterns()
        popular_dishes = self.analyze_popular_dishes()

        # 生成建议
        recommendations = {
            "时间策略": [
                f"在高峰时段（{', '.join(map(str, peak_times.get('高峰小时', [])))}点）增加人手，提高服务效率",
                f"在高峰日（{', '.join(peak_times.get('高峰星期', []))}）推出特别优惠或套餐",
                "在非高峰时段提供折扣，平衡客流"
            ],
            "菜单策略": [
                "重点推广热门菜品" + (f"，如 {', '.join([item['菜品名称'] for item in popular_dishes.get('热门菜品', [])[:3]])}" if popular_dishes.get('热门菜品', []) else ""),
                "对冷门菜品考虑调整价格或菜品描述，提高吸引力"
            ],
            "营销策略": [
                "根据地区偏好调整营销策略",
                "建立会员制度，提高客户粘性",
                "利用社交媒体推广热门菜品图片",
                "针对高消费顾客提供个性化服务"
            ],
            "其他建议": [
                "延长营业时间，覆盖更多潜在顾客",
                "优化点餐流程，提高用户体验",
                "考虑与外卖平台合作，扩大客源"
            ]
        }

        return recommendations

    def run_analysis(self, restaurant_id=None):
        """运行所有分析并返回结果"""
        results = {}

        print("分析订单多的餐厅特点...")
        results["餐厅特点分析"] = self.analyze_popular_restaurants()

        print("分析订单时间模式...")
        results["订单时间分析"] = self.analyze_order_time_patterns()

        print("分析热门菜品...")
        results["热门菜品分析"] = self.analyze_popular_dishes()

        if restaurant_id:
            print(f"分析餐厅 {restaurant_id} 的详细情况...")
            results["餐厅详细分析"] = self.analyze_restaurant_details(restaurant_id)

        print("生成增加订单的建议...")
        results["增加订单建议"] = self.recommendations_for_increasing_orders()

        return results

# 主函数
def main():
    try:
        # 创建命令行参数解析器
        parser = argparse.ArgumentParser(description='餐厅数据分析工具')
        parser.add_argument('-r', '--restaurant', help='餐厅数据文件路径', default=CONFIG["restaurant_file"])
        parser.add_argument('-o', '--order', help='订单数据文件路径', default=CONFIG["order_file"])
        parser.add_argument('-d', '--output-dir', help='输出目录', default=CONFIG["output_dir"])
        parser.add_argument('-i', '--restaurant-id', help='指定分析的餐厅ID')
        parser.add_argument('-s', '--show-plots', help='显示图表', action='store_true')
        parser.add_argument('-c', '--config', help='配置文件路径')

        args = parser.parse_args()

        # 如果指定了配置文件，从配置文件加载设置
        if args.config:
            try:
                with open(args.config, 'r', encoding='utf-8') as f:
                    config_data = json.load(f)
                    for key, value in config_data.items():
                        if key in CONFIG:
                            CONFIG[key] = value
                print(f"已从 {args.config} 加载配置")
            except Exception as e:
                print(f"加载配置文件时出错: {e}")

        # 命令行参数优先级高于配置文件
        CONFIG["restaurant_file"] = args.restaurant
        CONFIG["order_file"] = args.order
        CONFIG["output_dir"] = args.output_dir
        if args.restaurant_id:
            CONFIG["specific_restaurant_id"] = args.restaurant_id
        CONFIG["show_plots"] = args.show_plots

        # 创建分析器
        analyzer = RestaurantAnalyzer(
            CONFIG["restaurant_file"],
            CONFIG["order_file"],
            CONFIG["output_dir"]
        )

        # 运行分析
        if CONFIG["specific_restaurant_id"]:
            restaurant_id = CONFIG["specific_restaurant_id"]
            print(f"指定分析餐厅 ID: {restaurant_id}")
            results = analyzer.run_analysis(restaurant_id)
        else:
            # 如果没有通过命令行参数指定餐厅ID，则交互式询问
            restaurant_id = input("请输入要分析的餐厅ID（直接回车则不分析特定餐厅）: ")
            if restaurant_id:
                results = analyzer.run_analysis(restaurant_id)
            else:
                results = analyzer.run_analysis()

        # 输出结果
        print("\n======= 分析结果 =======")

        print("\n1. 订单多的餐厅特点:")
        restaurant_features = results["餐厅特点分析"]
        if restaurant_features:
            for i, restaurant in enumerate(restaurant_features):
                print(f"  {i+1}. {restaurant.get('餐厅名称', '未知')} (ID: {restaurant.get('餐厅ID', '未知')}): {restaurant.get('订单数', 0)} 单")
        else:
            print("  没有足够的数据分析餐厅特点")

        print("\n2. 订单爆发的时间:")
        time_analysis = results["订单时间分析"]
        print(f"  高峰小时: {', '.join(map(str, time_analysis.get('高峰小时', [])))}")
        print(f"  高峰星期: {', '.join(time_analysis.get('高峰星期', []))}")

        print("\n3. 热门菜品分析:")
        dish_analysis = results["热门菜品分析"]
        print("  热门菜品TOP10:")
        if dish_analysis.get("热门菜品", []):
            for dish in dish_analysis.get("热门菜品", []):
                print(f"    - {dish['菜品名称']}: {dish['点单次数']}次, 平均价格: ${dish['平均价格']:.2f}")
        else:
            print("    没有足够的数据分析热门菜品")

        print("\n  热门菜品类别:")
        if dish_analysis.get("热门菜品类别", []):
            for category in dish_analysis.get("热门菜品类别", []):
                print(f"    - {category['菜品类别']}: {category['数量']}次")
        else:
            print("    没有足够的数据分析菜品类别")

        if "餐厅详细分析" in results:
            print("\n4. 餐厅详细分析:")
            detail = results["餐厅详细分析"]
            if "错误" in detail:
                print(f"  {detail['错误']}")
            else:
                print(f"  餐厅名称: {detail.get('餐厅名称', '未知')}")
                print(f"  订单总数: {detail.get('订单总数', 0)}")
                if "平均订单金额" in detail:
                    print(f"  平均订单金额: ${detail['平均订单金额']:.2f}")

                print("  热门菜品:")
                if detail.get("热门菜品", []):
                    for dish in detail.get("热门菜品", [])[:5]:
                        print(f"    - {dish['菜品名称']}: {dish['点单次数']}次, 平均价格: ${dish['平均价格']:.2f}")
                else:
                    print("    没有热门菜品数据")

                if "高峰时段" in detail:
                    print(f"  高峰时段: {', '.join(map(str, detail['高峰时段']))}")
                if "高峰星期" in detail:
                    print(f"  高峰星期: {', '.join(detail['高峰星期'])}")

        print("\n5. 增加订单的建议:")
        for category, items in results["增加订单建议"].items():
            print(f"\n  {category}:")
            for item in items:
                print(f"    - {item}")

        print(f"\n分析结果图表已保存到 {CONFIG['output_dir']} 目录")

    except Exception as e:
        print(f"分析过程中发生错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()
